﻿// // ******************************************************************
// //       /\ /|       @file       UserDataCommandHandler.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-11-03 16:11
// //    *(__\_\        @Copyright  Copyright (c) , 2024-11-03 11:11 Await
// // ******************************************************************

using AutomaticSubtitles.Contracts.Dto;
using AutomaticSubtitles.Service.Application.User.Commands;
using AutomaticSubtitles.Service.Domain.User;

namespace AutomaticSubtitles.Service.Application.User;

public class UserDataCommandHandler(IUserRepository repository):BaseAutoService
{
    [EventHandler]
    public async Task CreateLoginTokenCommand(CreateLoginTokenCommand command)
    {
        //文档地址https://docs.masastack.com/framework/utils/security/cryptography#section-52a05bc6
        var encrypt = DESUtils.Encrypt(command.data.password);
        var autoUser = await repository.FindAsync(x => x.Account == command.data.userName && x.Password == encrypt);
        if (autoUser == null || autoUser.IsDeleted || autoUser.IsFrozen) throw new Exception(ReturnMessage(LoginError));
        var claims = JwtHelper.GetClaimsIdentity(autoUser);
        var token = JwtHelper.GeneratorAccessToken(claims);
        var refreshToken = JwtHelper.GeneratorAccessToken(claims);
        autoUser.RefreshToken = refreshToken;
        autoUser.UpdateTime = DateTime.Now;
        await repository.UpdateAsync(autoUser);
        command.Result = new UserTokenDto()
        {
            Token = token,
            RefreshToken = refreshToken
        };
    }
}